import {
	login,
	getUserInfo,
	logout
} from '@/api/login'
export default {
	state: {
		uid: uni.getStorageSync('uni') || '',
		token: uni.getStorageSync('uniIdToken') || '',
		UseInfo: uni.getStorageSync('UseInfo') || ''
	},
	mutations: {
		setUid(state, uid) {
			state.uid = uid
			uni.setStorageSync('uni', uid)
		},
		setToken(state, token) {
			state.token = token
			uni.setStorageSync('uniIdToken', token)
		},
		setUserInfo(state, UseInfo) {
			state.UseInfo = UseInfo
			uni.setStorageSync('UseInfo', UseInfo)
		}
	},
	actions: {
		// 登录
		handleLogin({
			dispatch,
			commit
		}, userdata) {
			return new Promise(async (resolve, reject) => {
				try {
					var res = await login(userdata)
					commit('setUid', res.uid)
					commit('setToken', res.token)
					await dispatch('getUserInfo')
					return resolve(res)
				} catch (error) {
					reject(error)
				}
			})
		},
		// 获取用户相关信息
		getUserInfo({
			state,
			commit,
			dispatch
		}) {
			return new Promise(async (resolve, reject) => {
				try {
					var res = await getUserInfo()
					commit('setUserInfo', res)
					resolve()
				} catch (error) {}
			})
		},
		// 退出登录
		handleLogOut({
			commit
		}) {
			return new Promise(async (resolve, reject) => {
				try {
					await logout()
					commit('setUid', '')
					commit('setToken', '')
					commit('setUserInfo', '')
					resolve()
				} catch (error) {
					reject(error)
				}
			})
		}
	}
}
